﻿using System;
using System.Linq;
using DataAccess.Models;
using System.Collections.Generic;

namespace DataAccess.Repository
{
	public class UserRepository : IUserRepository, IDisposable
	{
		private KPIDbContext _KPIDBContext = new KPIDbContext();

		private User2 GetUser2FromReader(System.Data.Common.DbDataReader rd)
		{
			User2 result = null;

			if(rd != null)
			{
				var item = new User2();
				for(var i = 0; i < rd.FieldCount; i++)
				{
					switch(rd.GetName(i))
					{
						case "ID":
							{
								item.ID = Convert.ToInt32(rd[rd.GetName(i)]);
							}
							break;
						case "Username":
							{
								item.UserName = rd[rd.GetName(i)] == DBNull.Value ? string.Empty : Convert.ToString(rd[rd.GetName(i)]);
							}
							break;
						case "C_Name":
							{
								item.UserCName = rd[rd.GetName(i)] == DBNull.Value ? string.Empty : Convert.ToString(rd[rd.GetName(i)]);
							}
							break;
						case "DeptId":
							{
								item.DeptId = rd[rd.GetName(i)] == DBNull.Value ? 0 : Convert.ToInt32(rd[rd.GetName(i)]);
							}
							break;
						case "IsDocReceiver":
							{
								item.IsDocReceiver = rd[rd.GetName(i)] == DBNull.Value ? 0 : Convert.ToInt32(rd[rd.GetName(i)]);
							}
							break;
						case "MobileNO":
							{
								item.MobileNO = rd[rd.GetName(i)] == DBNull.Value ? string.Empty : Convert.ToString(rd[rd.GetName(i)]);
							}
							break;
						case "SectionOfficeID":
							{
								item.SectionOfficeID = rd[rd.GetName(i)] == DBNull.Value ? 0 : Convert.ToInt32(rd[rd.GetName(i)]);
							}
							break;
						case "Address":
							{
								item.Address = rd[rd.GetName(i)] == DBNull.Value ? string.Empty : Convert.ToString(rd[rd.GetName(i)]);
							}
							break;
						case "DeptName":
							{
								item.DeptName = rd[rd.GetName(i)] == DBNull.Value ? string.Empty : Convert.ToString(rd[rd.GetName(i)]);
							}
							break;
					}
				}

				result = item;
			}

			return result;
		}

		#region IDisposable Members

		public void Dispose()
		{
			if(_KPIDBContext != null)
			{
				_KPIDBContext.Dispose();
			}
		}

		#endregion

		#region IUserRepository Members

		/// <summary>
		/// 验证用户名和密码
		/// </summary>
		/// <param name="userName">用户名</param>
		/// <param name="pwd">密码</param>
		/// <param name="msg">返回信息</param>
		/// <returns>true: 验证成功/false: 验证失败</returns>
		public bool ValidUser(string userName, string pwd, out string msg)
		{
			var result = false;
			msg = string.Empty;

			if(!string.IsNullOrWhiteSpace(userName))
			{
				try
				{
					var encryptPwd = CommonHelper.Encrypt(pwd);

					if(_KPIDBContext.User.Count(u => u.UserName == userName) > 0)
					{
						if(_KPIDBContext.User.Count(u => u.UserName == userName && u.Password == encryptPwd) > 0)
						{
							result = true;
						}
						else
						{
							msg = "密码不正确";
						}
					}
					else
					{
						msg = "用户名不存在";
					}
				}
				catch
				{
					throw;
				}
			}

			return result;
		}

		/// <summary>
		/// 根据用户名获取用户
		/// </summary>
		/// <param name="userName">用户名</param>
		/// <returns></returns>
		public User GetUser(string userName)
		{
			User result = null;

			if(!string.IsNullOrWhiteSpace(userName))
			{
				try
				{
					result = _KPIDBContext.User.FirstOrDefault(u => u.UserName == userName);
				}
				catch
				{
					throw;
				}
			}

			return result;
		}

		/// <summary>
		/// 验证用户名和密码
		/// </summary>
		/// <param name="userName">用户名</param>
		/// <param name="pwd">密码</param>
		/// <param name="msg">返回信息</param>
		/// <returns>用户对象: 验证成功并返回该用户对象/Null: 验证不成功</returns>
		public User ValidUserAndGetUser(string userName, string pwd, out string msg)
		{
			User result = null;
			msg = string.Empty;

			if(!string.IsNullOrWhiteSpace(userName))
			{
				//try
				//{
				if(ValidUser(userName, pwd, out msg))
				{
					result = GetUser(userName);
				}
				//}
				//catch
				//{
				//  throw;
				//}
			}

			return result;
		}

		/// <summary>
		/// 修改用户信息
		/// </summary>
		/// <param name="theUser">用户对象</param>
		/// <param name="passwordReset">是否更新密码</param>
		/// <returns>true/false</returns>
		public bool UpdateUser(User theUser, bool passwordReset)
		{
			var result = false;

			if(theUser != null && theUser.UserID > 0)
			{
				try
				{
					var orgUser = _KPIDBContext.User.Find(theUser.UserID);

					if(orgUser != null)
					{
						if(!passwordReset)
						{
							theUser.Password = orgUser.Password;
						}
						else
						{
							theUser.Password = CommonHelper.Encrypt(theUser.Password);
						}
						theUser.ModifyTime = DateTime.Now;

						_KPIDBContext.Entry(orgUser).CurrentValues.SetValues(theUser);
						_KPIDBContext.SaveChanges();

						result = true;
					}
				}
				catch
				{
					throw;
				}
			}

			return result;
		}

		/// <summary>
		/// 从党政网数据库取用户
		/// </summary>
		/// <param name="userName">用户名</param>
		/// <returns></returns>
		public User2 GetUser2(string userName)
		{
			User2 result = null;

			if(!string.IsNullOrWhiteSpace(userName))
			{
				System.Data.Common.DbDataReader rd = null;

				try
				{
					_KPIDBContext.Database.Initialize(false);

					var cmd = _KPIDBContext.Database.Connection.CreateCommand();
					cmd.CommandText = "KPI_GetUser2";
					cmd.CommandType = System.Data.CommandType.StoredProcedure;

					System.Data.Common.DbParameter p1 = cmd.CreateParameter();
					p1.DbType = System.Data.DbType.String;
					p1.Direction = System.Data.ParameterDirection.Input;
					p1.ParameterName = "@USERNAME";
					p1.Value = userName;

					cmd.Parameters.Add(p1);

					_KPIDBContext.Database.Connection.Open();
					rd = cmd.ExecuteReader();

					if(rd.Read())
					{
						result = GetUser2FromReader(rd);
					}

					if(!rd.IsClosed)
					{
						rd.Close();
					}
				}
				catch
				{
					throw;
				}
			}

			return result;
		}

		/// <summary>
		/// 根据党政网用户单位名称获取KPI库中对应的单位
		/// </summary>
		/// <param name="name">党政网用户单位名称</param>
		/// <returns>单位</returns>
		public Group GetGroupByName(string name)
		{
			Group result = null;

			if(!string.IsNullOrWhiteSpace(name))
			{
				try
				{
					result = _KPIDBContext.Group.FirstOrDefault(g => g.GroupName == name);
				}
				catch
				{
					throw;
				}
			}

			return result;
		}

		/// <summary>
		/// 从党政网数据库根据部门取单位管理员
		/// </summary>
		/// <param name="deptID"></param>
		/// <returns></returns>
		public List<User2> GetDocRecieverByDept(int deptID)
		{
			List<User2> result = null;

			if(deptID > 0)
			{
				System.Data.Common.DbDataReader rd = null;

				try
				{
					_KPIDBContext.Database.Initialize(false);

					var cmd = _KPIDBContext.Database.Connection.CreateCommand();
					cmd.CommandText = "KPI_GetDocRecieverByDept";
					cmd.CommandType = System.Data.CommandType.StoredProcedure;

					System.Data.Common.DbParameter p1 = cmd.CreateParameter();
					p1.DbType = System.Data.DbType.Int32;
					p1.Direction = System.Data.ParameterDirection.Input;
					p1.ParameterName = "@DEPTID";
					p1.Value = deptID;

					cmd.Parameters.Add(p1);

					if(_KPIDBContext.Database.Connection.State != System.Data.ConnectionState.Open)
					{
						_KPIDBContext.Database.Connection.Open();
					}
					rd = cmd.ExecuteReader();

					while(rd.Read())
					{
						var item = GetUser2FromReader(rd);

						if(item != null)
						{
							if(result == null)
							{
								result = new List<User2>();
							}

							result.Add(item);
						}
					}

					if(!rd.IsClosed)
					{
						rd.Close();
					}
				}
				catch
				{
					throw;
				}
			}

			return result;
		}

		public List<User2> GetDocRecieversByGroups(List<int> groupIDs)
		{
			List<User2> result = null;

			if(groupIDs != null && groupIDs.Count > 0)
			{
				result = new List<User2>();

				try
				{
					foreach(var item in groupIDs)
					{
						var user2 = GetDocRecieverByDept(item);

						if(user2 != null && user2.Count > 0)
						{
							result.AddRange(user2);
						}
					}
				}
				catch
				{
					throw;
				}
			}

			return result;
		}

		#endregion
	}
}
